# !usr/bin/python
# -*-coding: utf-8-*-
# Filename: log.py

import time
import datetime

LOG_PATH = ''
LOG_NAME_PRE = 'LCOVE_'
LOG_NAME_SUF = '_LOG.log'
LOG_LEVEL_ERR = 0
LOG_LEVEL_WRN = 1
LOG_LEVEL_INF = 2
LOG_LEVEL_DBG = 3
LOG_RECORD = 1
LOG_LEVEL_STR = ( 'ERR', 'WRN', 'INF', 'DBG' )

class ENTRY:
	'''单条日志内容

	此类仅作存储数据用(结构体)'''
	def __init__( self, date, datastr, level ):
		self.Level = level
		self.Date = date
		self.Str = datastr


class LOG:
	'''输出日志到文件

	'''

	# 日志列表
	LogList = []

	def __init__( self, Log_Path=LOG_PATH, Log_Name_Pre=LOG_NAME_PRE, Log_Name_Suf=LOG_NAME_SUF ):
		self.date = datetime.datetime.now()
		self.logpatn = LOG_PATH + LOG_NAME_PRE + self.date + LOG_NAME_SUF
		self.count = 0

	def close( self ):
		self.write()

	def write( self ):
		i = 0
		# 打开文件
		fp = open( self.logpatn ,'ab')
		# 日志记录写入
		while( i < self.count ):
			if( self.date != self.LogList[i].Date ):
				# 关闭之前打开的文件
				if( fp != None ):
					fp.close()

				# 获取该条日志的日期
				self.date = self.LogList[i].Date
				self.logpatn = LOG_PATH + LOG_NAME_PRE + self.date + LOG_NAME_SUF
				# 打开文件
				fp = open( self.logpatn ,'a')

			data = '%s, %s, %s%s' % ( LOG_LEVEL_STR[ self.LogList[i].Level ], self.LogList[self.count-1].Date, self.LogList[self.count-1].Str, '\r\n' )
			fp.write( data )
			# 下一条记录
			i += 1

		# 清空列表
		self.LogList[:] = []

		# 关闭文件
		fp.close()

	def log( self, level=LOG_LEVEL_DBG, datastr=None  ):
		# 当前时间获取
		date = datetime.datetime.now()
		# 日志条目作成
		entry = ENTRY( date, datastr, level )
		# 向列表中添加记录
		self.LogList.append( entry )
		# 记录数增加
		self.count += 1
		# 达到最大容量则写入文件
		if( self.count >= LOG_RECORD ):
			self.write()

# mylog = LOG()
# mylog.log( LOG_LEVEL_DBG, 'hello!' )

print( time.time() )